/*
+--------------------------------------------------------------------------
|   Mblog [#RELEASE_VERSION#]
|   ========================================
|   Copyright (c) 2014, 2019 mtons. All Rights Reserved
|   http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package com.xdw.vuebackdemo.base.storage.impl;

import com.xdw.vuebackdemo.base.common.ApiCodeConstant;
import com.xdw.vuebackdemo.base.common.MyException;
import com.xdw.vuebackdemo.base.storage.Storage;
import com.xdw.vuebackdemo.config.SiteOptions;
import com.xdw.vuebackdemo.util.FileKit;
import com.xdw.vuebackdemo.util.FilePathUtils;
import com.xdw.vuebackdemo.util.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

/**
 * @author xiadewang
 * 存储抽象工厂类设计
 */
public abstract class AbstractStorage implements Storage {
    @Autowired
    protected SiteOptions options;

    protected void validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new MyException(ApiCodeConstant.RESULT_OTHER_EXCEPTION,"文件不能为空");
        }

        if (!FileKit.checkFileType(file.getOriginalFilename())) {
            throw new MyException(ApiCodeConstant.RESULT_OTHER_EXCEPTION,"文件格式不支持");
        }
    }

    @Override
    public String store(MultipartFile file, String basePath) throws Exception {
        validateFile(file);
        return writeToStore(file.getBytes(), basePath, file.getOriginalFilename());
    }

    @Override
    public String storeScale(MultipartFile file, String basePath, int maxWidth) throws Exception {
        validateFile(file);
        byte[] bytes = ImageUtils.scaleByWidth(file, maxWidth);
        return writeToStore(bytes, basePath, file.getOriginalFilename());
    }

    @Override
    public String storeScale(MultipartFile file, String basePath, int width, int height) throws Exception {
        validateFile(file);
        byte[] bytes = ImageUtils.screenshot(file, width, height);
        return writeToStore(bytes, basePath, file.getOriginalFilename());
    }

    public String writeToStore(byte[] bytes, String src, String originalFilename) throws Exception {
        String md5 = DigestUtils.md5DigestAsHex(bytes);
        String path = FilePathUtils.wholePathName(src, originalFilename);
        path = writeToStore(bytes, path);
        return path;
    }

}
